<template>
  <div>
    <div style="display:flex; justify-content:flex-end; margin-bottom: 8px;">
      <el-button type="success" @click="openMainDialog()">新增</el-button>
      <!-- <el-button type="primary" @click="exportList">导出</el-button> -->
      <el-button type="danger" :disabled="!logic.hasSelection" @click="deleteSelected">删除</el-button>
    </div>

      <el-form :inline="true" :model="model" class="demo-form-inline">
    <el-form-item label="名称">
      <el-input v-model="model.DesignName"  clearable />
    </el-form-item>
    <el-form-item label="类型">
      <el-select
        v-model="model.DesugbType"
        
        clearable
      >
        <el-option label="全检" :value="1" />
        <el-option label="抽检" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="fetchList">查询</el-button>
    </el-form-item>
  </el-form>
     
      
  
    <el-table
      ref="tableRef"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="onSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column prop="designName" label="名称" min-width="160" />
      <el-table-column prop="desugbType" label="类型" width="100">
        <template v-slot="scope">
          <el-tag type="warning" v-if="scope.row.desugbType==1">全检</el-tag>
          <el-tag type="danger" v-else>抽检</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="inspectionMethod" label="抽检方式" width="120" >
         <template v-slot="scope">
          <el-tag type="warning" v-if="scope.row.inspectionMethod==1">百分比</el-tag>
          <el-tag type="danger" v-else>间隔</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="designValue" label="值" width="160" />
      <el-table-column prop="examineProjectName" label="描述" min-width="180" />
      <el-table-column prop="createName" label="创建人" width="140" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button link type="primary" @click="openMainDialog(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="deleteOne(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="display:flex; justify-content:flex-end; margin-top: 8px;">
      <el-pagination
        v-model:current-page="paging.pageIndex"
        v-model:page-size="paging.pageSize"
        :page-sizes="[10,20,30,40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.totalCount"
      />
    </div>

    <!-- 新增/编辑主对话框 -->
    <el-dialog v-model="logic.dialogOpen" :title="logic.dialogTitle" width="700" align-center draggable>
      <el-form :model="form" :label-width="120">
        <el-form-item label="名称" required>
          <el-input v-model="form.designName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-radio-group v-model="form.desugbType">
            <el-radio :value="1">全检</el-radio>
            <el-radio :value="2" @change="Open">抽检</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-show="form.desugbType!=1">
        <el-form-item label="抽检方式">
           <el-radio-group v-model="form.inspectionMethod">
            <el-radio :value="1">百分比</el-radio>
            <el-radio :value="2">间隔</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-show="form.inspectionMethod==1">
                 <el-form-item label="值">
             <el-input-number
                v-model="form.designValue"
                :min="0"
                :max="10"
                controls-position="right"
                 @change="handleChange"
                />%
        
        </el-form-item>
         </div>
         <div v-show="form.inspectionMethod==2">
              <el-form-item label="值">
            <el-input v-model="form.designValue"/>
                
        </el-form-item>
         </div>
          
        
        
        </div>
        <el-form-item label="检验项目">
          <el-input v-model="form.examineProjectName" placeholder="请选择检验项目">
            <template #suffix>
              <el-icon style="cursor:pointer" @click="openNestedSelector"><arrow-down /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.designDescription" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="logic.dialogOpen = false">取消</el-button>
          <el-button type="primary" @click="saveMain">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 嵌套对话框：选择检验项目    -->
    <el-dialog v-model="nested.open" title="选择数据" width="900" align-center draggable>
      <el-table :data="nested.textMent" style="width:100%">
        <el-table-column type="selection" width="55" @current-change="onNestedCurrentChange">
          <template #default="scope">
            <el-radio v-model="nested.currentId" :label="scope.row.examineProjectId" />
          </template>
        </el-table-column>
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="examineProjectName" label="名称" min-width="220" />
        <el-table-column prop="projectMethod" label="类型" width="120" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="nested.open = false">取消</el-button>
          <el-button type="primary" @click="confirmNested">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { APIs } from '@/Http/http'

const tableRef = ref()
const tableData = ref<any[]>([])

// 是否使用本地死数据
const useMock = true

/* const mockRows = [
  {
    id: 1,
    name: 'TEST',
    type: 'sample',
    typeName: '抽检',
    sampleMethodName: '百分比',
    sampleValueText: '10%',
    remark: '',
    creatorName: '(test)程腾管理员',
    createdAt: '2024-07-06 10:16:18',
    updatedAt: '2025-08-23 10:38:47'
  },
  {
    id: 2,
    name: '出厂检验',
    type: 'sample',
    typeName: '抽检',
    sampleMethodName: '间隔',
    sampleValueText: '每间隔5抽取1',
    remark: '',
    creatorName: '(admin)系统管理员',
    createdAt: '2024-08-02 11:35:42',
    updatedAt: '2025-09-03 17:27:09'
  },
  {
    id: 3,
    name: '测试',
    type: 'sample',
    typeName: '抽检',
    sampleMethodName: '百分比',
    sampleValueText: '30%',
    remark: '',
    creatorName: '(admin)系统管理员',
    createdAt: '2024-08-05 17:22:51',
    updatedAt: '2025-08-06 09:43:28'
  },
  {
    id: 4,
    name: '测试0914',
    type: 'all',
    typeName: '全检',
    sampleMethodName: '',
    sampleValueText: '',
    remark: '',
    creatorName: '(test)程腾管理员',
    createdAt: '2024-09-14 11:35:41',
    updatedAt: '2025-03-28 15:36:45'
  }
] */

const paging = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  total:1
})

watch(() => [paging.pageIndex, paging.pageSize], () => {
  if (!useMock) fetchList()
})

onMounted(() => {
  
    fetchList()

})

const logic = reactive({
  hasSelection: false,
  dialogOpen: false,
  dialogTitle: '新增',
  isAdd: true,
  isOpen:false,
  isOpenGo:false
})
const Open=()=>{

    logic.isOpen=true;
    
}
const openMainDialog = (row?: any) => {
  logic.dialogOpen = true
  if (!row) {
    logic.isAdd = true
    logic.dialogTitle = '新增'
    form.designId=0,
    form.designName="",
    form.desugbType=0,
    form.inspectionMethod=0,
    form.designValue=0,
    form.examineProjectName="",
    form.designDescription=""

    

  } else {
    logic.isAdd = false
    logic.dialogTitle = '编辑'
     form.designId=row.designId,
    form.designName=row.designName,
    form.desugbType=row.desugbType,
    form.inspectionMethod=row.inspectionMethod,
    form.designValue=row.designValue,
    form.examineProjectName=row.examineProjectName,
    form.designDescription=row.designDescription
    
  }
}


const selectedRows = ref<any[]>([])

const form = reactive({
  designId:0,
  designName: "",
  desugbType: 0,
  inspectionMethod: 0,
  designValue: 0,
  examineProjectName: "",
  designDescription: ""
})
const handleChange = (value: number | undefined) => {
 form.designValue==value;
  
}
const model=reactive({
  DesignName:"",
  DesugbType:""
})

const nested = reactive({
  open: false,
  textMent:ref<any>([]),
  currentId:""
})

const fetchList = () => {
  APIs.get('/api/Read/GetExaminDesign', {
    params: {
    DesignName:model.DesignName,
    DesugbType:model.DesugbType || 0,
      PageIndex: paging.pageIndex,
      PageSize: paging.pageSize
    }
  }).then(res => {
     tableData.value=res.data.data.data ;
     paging.totalCount=res.data.data.totalCount
     paging.total=res.data.data.total
  })
}

const onSelectionChange = (val: any[]) => {
  selectedRows.value = val
  console.log(selectedRows.value);
  logic.hasSelection = val.length > 0
}



const saveMain = () => {
    
  if (!form.designName) {
    ElMessage.warning('请填写名称')
    return
  }
  if(logic.isAdd)
  {
    /* let command=reactive<any>({})
    command.designId=form.designId
    command.designName=form.designName;
      command.desugbType=form.desugbType
     command.inspectionMethod=form.inspectionMethod
     command.designValue=JSON.stringify(form.designValue)
    command.examineProjectName=form.examineProjectName
    command.designDescription=form.designDescription */
   
  APIs.post("/api/Write/AddExamineDesign",form).then(res=>{
  if(res.data.code==100)
 {
     ElMessage.success(res.data.msg);
     nested.open=false;
     fetchList();
      
 }
 else
 {
  ElMessage.error(res.data.msg);
  return;
 }
 })
}
else
{
   let command=reactive<any>({})
   command.designId=form.designId
    command.designName=form.designName;
      command.desugbType=form.desugbType
     command.inspectionMethod=form.inspectionMethod
     command.designValue=JSON.stringify(form.designValue)
    command.examineProjectName=form.examineProjectName
    command.designDescription=form.designDescription
   
  APIs.post("/api/Write/UpdateExamineDesign",command).then(res=>{
  if(res.data.code==100)
 {
     ElMessage.success(res.data.msg);
  
 nested.open=false;
         fetchList();

 }
 else
 {
  ElMessage.error(res.data.msg);
  return;
 }
 })
}
  
 
}

const deleteOne = (row: any) => {
  ElMessageBox.confirm('确认要删除吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    APIs.delete('/api/Write/DeleteExaminDesign', { params: { designId: row.designId } }).then(res => {
      if (res.data.code === 100) {
        ElMessage.success(res.data.msg || '删除成功')
        fetchList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    })
  })
}

const deleteSelected = () => {
  const designs = selectedRows.value.map(r => r.designId).toString()
  if (!designs) return
  ElMessageBox.confirm('确认要删除吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    APIs.delete('/api/Write/AllDeleteExamineDesign', { params: { designs:designs } }).then(res => {
      if (res.data.code === 100) {
        ElMessage.success(res.data.msg || '删除成功')
        fetchList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    })
  }).catch(() => {})
}

const exportList = () => {
  APIs.get('/api/Read/ExportQualityDesigns', { responseType: 'blob' }).then(res => {
    const blob = new Blob([res.data], { type: 'application/octet-stream' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '质量检验方案.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  })
}

const openNestedSelector = () => {
  nested.open = true
  loadNested()
}

const loadNested = () => {
  APIs.get('/api/Read/ShowProject').then(res => {
     nested.textMent=res.data.data;   

  })
}



const onNestedCurrentChange = (row: any) => {
  if (row && row.id) nested.currentId = row.examineProjectId
}

const confirmNested = () => {
  const row = nested.textMent.find((r: any) => r.examineProjectId === nested.currentId)
  if (!row) {
    ElMessage.warning('请选择数据')
    return
  }
 
  form.examineProjectName = row.examineProjectName
  nested.open = false
}
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>

